package cn.shengchao.order;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.shengchao.base.enums.ProductType;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeContentInfo;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeContentProductThird;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeNodeInfo;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeContentInfoService;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeContentProductThirdService;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeNodeInfoService;
import cn.shengchao.examstar.distribute.infrastrure.service.DistributeOrderTaskContentService;
import cn.shengchao.examstar.pay.acl.ports.repositories.IOrderRepository;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeContentRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeDataStatusEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import cn.shengchao.examstar.rpc.orders.api.IOrderViewQueryRpc;
import cn.shengchao.examstar.rpc.orders.req.*;
import cn.shengchao.examstar.rpc.orders.res.OrderList;
import cn.shengchao.examstar.rpc.product.base.ContentProductType;
import cn.shengchao.examstart.user.acl.adapters.repositories.UserRepository;
import cn.shengchao.examstart.user.domain.entity.User;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import top.continew.starter.extension.crud.model.entity.BaseDO;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @program: examstarapi
 * @description: 订单查询
 * @author: Xiong weiqiang
 * @create: 2025-06-12 15:45
 */
@DubboService
public class OrderViewQueryRpc implements IOrderViewQueryRpc {
    @Autowired
    private IOrderRepository orderRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private DistributeContentInfoService distributeContentInfoService;
    @Autowired
    private DistributeOrderTaskContentService distributeOrderTaskContentService;
    @Autowired
    private DistributeNodeInfoService distributeNodeInfoService;
    @Autowired
    private DistributeContentProductThirdService distributeContentProductThirdService;

    @Override
    public List<SubOrderWithSupplierView> subOrderListForOrderId(Long orderId) {
        List<SubOrderWithSupplierView> list = orderRepository.selectSubOrderListByOrderId(orderId);
        List<Long> userIds = list.stream().map(SubOrderWithSupplierView::getUserId).distinct().toList();
        if (CollUtil.isNotEmpty(userIds)) {
            List<User> users = userRepository.getUserList(userIds);
            if (CollUtil.isNotEmpty(users)) {
                for (SubOrderWithSupplierView item : list) {
                    User user = users.stream().filter(u -> u.getId().equals(item.getUserId())).findFirst().orElse(null);
                    if (user != null) {
                        item.setUserName(user.getName());
                        item.setUserPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
                    }
                }
            }
        }
        return list;
    }

    @Override
    public PageResult<SubOrderWithSupplierView> subOrderPageFromMainOrder(SubOrderForMainPageQuery subOrderForMainPageQuery) {
        try (Page<SubOrderWithSupplierView> page = PageHelper.startPage(subOrderForMainPageQuery.getPage(), subOrderForMainPageQuery.getSize())){
            List<SubOrderWithSupplierView> list = orderRepository.selectSubOrderListFromMainOrder(subOrderForMainPageQuery);
            return PageResult.of(page.getTotal(), list);
        }

    }

    @Override
    public PageResult<OrderWithSupplierView> pageList(OrderWithSupplierPageQuery orderWithSupplierPageQuery) {
        //支付用户手机号查询
        if (StrUtil.isNotBlank(orderWithSupplierPageQuery.getMobile())) {
            List<User> users = userRepository.selectByPhone(orderWithSupplierPageQuery.getMobile());
            if (CollUtil.isNotEmpty(users)) {
                orderWithSupplierPageQuery.setPayUserIds(users.stream().map(User::getId).toList());
            } else {
                return PageResult.of(0L, List.of());
            }
        }
        if (StrUtil.isNotBlank(orderWithSupplierPageQuery.getSupplierName())) {
            List<DistributeNodeInfo> distributeNodeInfos = distributeNodeInfoService.list(
                    Wrappers.lambdaQuery(DistributeNodeInfo.class)
                            .like(DistributeNodeInfo::getFullName, orderWithSupplierPageQuery.getSupplierName())
                            .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                            .eq(DistributeNodeInfo::getDistributeRoleCode, DistributeContentRoleEnum.ROLE_CTPD.getCode())
                            .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_CTPD.getType())
            );
            if (CollUtil.isNotEmpty(distributeNodeInfos)) {
                orderWithSupplierPageQuery.setContentUserIds(distributeNodeInfos.stream().map(DistributeNodeInfo::getUserId).toList());
            } else {
                return PageResult.of(0L, List.of());
            }
        }
        long total = 0L;
        try (Page<OrderWithSupplierView> page = PageHelper.startPage(orderWithSupplierPageQuery.getPage(), orderWithSupplierPageQuery.getSize())) {
            List<OrderWithSupplierView> list = orderRepository.selectOrderViewListByPageQuery(orderWithSupplierPageQuery);
            total = page.getTotal();
            BigDecimal sumAmount = orderRepository.countOrderViewAmountByPageQuery(orderWithSupplierPageQuery);
            Map<Long, Integer> subOrderNumMap = new HashMap();
            if (CollUtil.isNotEmpty(list)) {
                List<Long> orderIds = list.stream().map(OrderWithSupplierView::getOrderId).distinct().toList();
                List<OrderList> orderImgList = orderRepository.getOrderImgList(orderIds);
                Map<Long, OrderList> orderImgMap = orderImgList.stream().collect(Collectors.toMap(OrderList::getOrderId, item -> item));
                for (OrderWithSupplierView item : list) {
                    OrderList orderList = orderImgMap.get(item.getOrderId());
                    item.setImageUrl(orderList==null?"":orderList.getImageUrl());
                }
                List<CompletableFuture<Void>> futureList = orderIds.stream().map(orderId -> CompletableFuture.runAsync(() -> {
                    Integer subOrderNum = orderRepository.countOrderByOrderId(orderId.toString());
                    subOrderNumMap.put(orderId, subOrderNum);
                })).toList();
                futureList.forEach(CompletableFuture::join);
                List<Long> userIds = list.stream().map(OrderWithSupplierView::getUserId).distinct().toList();
                if (CollUtil.isNotEmpty(userIds)) {
                    List<User> users = userRepository.getUserList(userIds);
                    if (CollUtil.isNotEmpty(users)) {
                        for (OrderWithSupplierView item : list) {
                            User user = users.stream().filter(u -> u.getId().equals(item.getUserId())).findFirst().orElse(null);
                            if (user != null) {
                                item.setUserName(user.getName());
                                item.setUserPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
                            }
                        }
                    }
                }
                //供应商
                if (CollUtil.isNotEmpty(list)) {
                    List<CompletableFuture<Void>> supplierfutureList = list.stream().map(item -> CompletableFuture.runAsync(() -> {
                        if (List.of(ProductType.PRODUCT_THIRD_CAP.name(), ProductType.PRODUCT_THIRD_YCBDC.name()).contains(item.getProductType())) {
                            List<DistributeNodeInfo> distributeNodeInfos = distributeOrderTaskContentService.selectProductThirdDistributeNodeInfoListByOrderId(item.getOrderId());
                            if (CollUtil.isEmpty(distributeNodeInfos)) {
                                item.setSuppliers("平台");
                            } else {
                                item.setSuppliers(StrUtil.join(",", distributeNodeInfos.stream().filter(a -> a.getUserId() != null).distinct().map(DistributeNodeInfo::getFullName).toList()));
                            }
                        } else if (item.getProductType().equals(ContentProductType.COURSE.name())) {
                            List<DistributeNodeInfo> distributeNodeInfos = distributeOrderTaskContentService.selectCourseDistributeNodeInfoListByOrderId(item.getOrderId());
                            if (CollUtil.isEmpty(distributeNodeInfos)) {
                                item.setSuppliers("平台");
                            } else {
                                item.setSuppliers(StrUtil.join(",", distributeNodeInfos.stream().filter(a -> a.getUserId() != null).distinct().map(DistributeNodeInfo::getFullName).toList()));
                            }
                        } else {
                            item.setSuppliers("平台");
                        }
                    })).toList();
                    supplierfutureList.forEach(CompletableFuture::join);
                    for (OrderWithSupplierView item : list) {
                        item.setSubOrderNum(subOrderNumMap.getOrDefault(item.getOrderId(), 0));
                        if (List.of(ProductType.PRODUCT_THIRD_CAP.name(), ProductType.PRODUCT_THIRD_YCBDC.name()).contains(item.getProductType())) {
                            item.setOrderType(ContentProductType.THIRD_MEMBER.name());
                        } else {
                            item.setOrderType(item.getProductType());
                        }
                    }

                }
            }
            PageResult<OrderWithSupplierView> pageResult = PageResult.of(total, list);
            pageResult.setExtensions(new JSONObject().set("sumAmount", sumAmount));
            return pageResult;
        }
    }

    @Override
    public PageResult<SubOrderWithSupplierView> subOrderPageList(SubOrderWithSupplierPageQuery subOrderWithSupplierPageQuery) {
        if (subOrderWithSupplierPageQuery.getUserId() != null && subOrderWithSupplierPageQuery.getUserId() != 0L) {
            DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(subOrderWithSupplierPageQuery.getUserId(), DistributeTypeEnum.TYPE_CTPD);
            if (distributeNodeInfo != null) {
                //如果是员工，只能看属于自己的订单
                if (distributeNodeInfo.getDistributeRoleCode().equals(DistributeContentRoleEnum.ROLE_CTPD_EMP.getCode())) {
                    subOrderWithSupplierPageQuery.setDistributeUserIds(List.of(distributeNodeInfo.getUserId()));
                    subOrderWithSupplierPageQuery.setSourceContentUserId(distributeNodeInfo.getUserId());
                } else {
                    subOrderWithSupplierPageQuery.setDistributeUserIds(List.of(distributeNodeInfo.getUserId()));
                }
            }

        }
        if (StrUtil.isNotBlank(subOrderWithSupplierPageQuery.getSupplierName())) {
            if ("平台".equals(subOrderWithSupplierPageQuery.getSupplierName())){
                subOrderWithSupplierPageQuery.setSourceContentUserId(0L);
            }else {
                List<DistributeNodeInfo> distributeNodeInfos = distributeNodeInfoService.list(
                        Wrappers.lambdaQuery(DistributeNodeInfo.class)
                                .like(DistributeNodeInfo::getFullName, subOrderWithSupplierPageQuery.getSupplierName())
                                .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                                .eq(DistributeNodeInfo::getDistributeRoleCode, DistributeContentRoleEnum.ROLE_CTPD.getCode())
                                .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_CTPD.getType())
                );
                if (CollUtil.isNotEmpty(distributeNodeInfos)) {
                    subOrderWithSupplierPageQuery.setDistributeUserIds(distributeNodeInfos.stream().map(DistributeNodeInfo::getUserId).toList());
                } else {
                    return PageResult.of(0L, List.of());
                }
            }

        }
        //支付用户手机号查询
        if (StrUtil.isNotBlank(subOrderWithSupplierPageQuery.getMobile())) {
            List<User> users = userRepository.selectByPhone(subOrderWithSupplierPageQuery.getMobile());
            if (CollUtil.isNotEmpty(users)) {
                subOrderWithSupplierPageQuery.setPayUserIds(users.stream().map(User::getId).toList());
            } else {
                return PageResult.of(0L, List.of());
            }
        }
        long total = 0L;
        try (Page<SubOrderWithSupplierView> page = PageHelper.startPage(subOrderWithSupplierPageQuery.getPage(), subOrderWithSupplierPageQuery.getSize())) {
            List<SubOrderWithSupplierView> list = orderRepository.selectSubOrderViewListByPageQuery(subOrderWithSupplierPageQuery);
            total = page.getTotal();
            Map<String, BigDecimal> sumAmountMap = orderRepository.countSubOrderViewAmountByPageQuery(subOrderWithSupplierPageQuery);
            if (CollUtil.isNotEmpty(list)) {
                List<Long> userIds = list.stream().map(SubOrderWithSupplierView::getUserId).distinct().toList();
                if (CollUtil.isNotEmpty(userIds)) {
                    List<User> users = userRepository.getUserList(userIds);
                    if (CollUtil.isNotEmpty(users)) {
                        for (SubOrderWithSupplierView item : list) {
                            User user = users.stream().filter(u -> u.getId().equals(item.getUserId())).findFirst().orElse(null);
                            if (user != null) {
                                item.setUserName(user.getName());
                                item.setUserPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
                            }
                        }
                    }
                }
                //供应商
                if (CollUtil.isNotEmpty(list)) {
                    for (SubOrderWithSupplierView item : list) {
                        if (List.of(ProductType.PRODUCT_THIRD_CAP.name(), ProductType.PRODUCT_THIRD_YCBDC.name()).contains(item.getProductType())) {
                            item.setOrderType(ContentProductType.THIRD_MEMBER.name());
                        } else {
                            item.setOrderType(item.getProductType());
                        }
                        if (item.getProductType().equals(ContentProductType.COURSE.name())) {
                            List<DistributeContentInfo> distributeContentInfos = distributeContentInfoService
                                    .list(Wrappers.lambdaQuery(DistributeContentInfo.class)
                                            .eq(DistributeContentInfo::getContentId, item.getProductId())
                                            .le(DistributeContentInfo::getValidStartTime, item.getOrderTime())
                                            .ge(DistributeContentInfo::getValidEndTime, item.getOrderTime())
                                            .orderByDesc(BaseDO::getUpdateTime)
                                    );
                            if (CollUtil.isNotEmpty(distributeContentInfos)) {
                                List<Long> distributeUserIds = distributeContentInfos.stream().map(DistributeContentInfo::getContentDistributeUserId).distinct().toList();
                                List<DistributeNodeInfo> distributeNodeInfos = distributeNodeInfoService.list(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                                        .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_CTPD.getType())
                                        .eq(DistributeNodeInfo::getDataStatus, 1)
                                        .in(DistributeNodeInfo::getUserId, distributeUserIds));
                                //过滤一下是哪个供应商的
                                if (CollUtil.isNotEmpty(distributeNodeInfos) && item.getDistributeUserId() != null) {
                                    distributeNodeInfos = distributeNodeInfos.stream().filter(nodeInfo -> nodeInfo.getUserId().equals(item.getDistributeUserId()) || nodeInfo.getUserId().equals(subOrderWithSupplierPageQuery.getUserId())
                                    ).toList();
                                }
                                item.setSuppliers(StrUtil.join(",", distributeNodeInfos.stream().map(DistributeNodeInfo::getFullName).toList()));
                            } else {
                                item.setSuppliers("平台");
                            }
                        } else {
                            List<DistributeContentProductThird> distributeContentProductThirds = distributeContentProductThirdService
                                    .list(Wrappers.lambdaQuery(DistributeContentProductThird.class)
                                            .eq(DistributeContentProductThird::getProductId, item.getProductId())
                                            .lt(DistributeContentProductThird::getValidStartTime, item.getOrderTime())
                                            .ge(DistributeContentProductThird::getValidEndTime, item.getOrderTime())
                                            .orderByDesc(BaseDO::getUpdateTime)
                                    );
                            List<Long> distributeUserIds = distributeContentProductThirds.stream().map(DistributeContentProductThird::getContentDistributeUserId).distinct().toList();
                            if (CollUtil.isEmpty(distributeUserIds)) {
                                item.setSuppliers("平台");
                            } else {
                                List<DistributeNodeInfo> distributeNodeInfos = distributeNodeInfoService.list(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                                        .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_CTPD.getType())
                                        .eq(DistributeNodeInfo::getDataStatus, 1)
                                        .in(DistributeNodeInfo::getUserId, distributeUserIds));
                                //过滤一下是哪个供应商的
                                if (CollUtil.isNotEmpty(distributeNodeInfos) && item.getDistributeUserId() != null) {
                                    distributeNodeInfos = distributeNodeInfos.stream().filter(nodeInfo -> nodeInfo.getAdminUserId().equals(item.getDistributeUserId()) || nodeInfo.getUserId().equals(item.getDistributeUserId())
                                    ).distinct().toList();
                                }
                                item.setSuppliers(StrUtil.join(",", distributeNodeInfos.stream().map(DistributeNodeInfo::getFullName).toList()));
                            }

                        }
                    }

                }
            }
            PageResult<SubOrderWithSupplierView> pageResult = PageResult.of(total, list);
            pageResult.setExtensions(new JSONObject(sumAmountMap));
            return pageResult;
        }
    }
}